package com.ch.clinking.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.adapter.Order.EditOrderAdapter;
import com.ch.clinking.bean.Order;
import com.ch.clinking.bean.OrderDto;
import com.ch.clinking.bean.OrderInfo;
import com.ch.clinking.databinding.ActivityEditOrderBinding;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EditOrderActivity extends AppCompatActivity {

    private ActivityEditOrderBinding binding;

    private List<OrderInfo> orderInfoList;
    private EditOrderAdapter addOrderAdapter;
    private RecyclerView.LayoutManager layoutManager;

    private Order order;

    private ClinkingApplication app;
    private OrderDto orderDto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityEditOrderBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置状态栏图标为深色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        app = ClinkingApplication.getInstance();

        Intent intent = getIntent();
        orderDto = (OrderDto) intent.getSerializableExtra("orderDto");
        if (orderDto != null) {


            orderInfoList = new ArrayList<>();
            setMerMap(orderDto);
            addOrderAdapter = new EditOrderAdapter(EditOrderActivity.this, orderInfoList);
            binding.addOrderSkuStockList.setAdapter(addOrderAdapter);
            layoutManager = new LinearLayoutManager(this);
            binding.addOrderSkuStockList.setLayoutManager(layoutManager);
            binding.addOrderMerTitle.setText(orderDto.getTitle());
            binding.addOrderMerSkcId.setText(orderDto.getSkcId());
            binding.addOrderAddSKCProductNum.setText(orderDto.getProductNumber());
            binding.addOrderMerCreateTime.setText(orderDto.getCreatedTime().substring(0, orderDto.getCreatedTime().length() - 3));
        }

        Glide.with(EditOrderActivity.this).load(OkHttpUtil.getInstance().getIMG_URL() + orderDto.getFirstImage()).into(binding.addOrderMerImg);

        binding.addOrderStockCommit.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View view) {

                showLoading();

                String shopId = app.shopList.get(app.shopPosition).getShopId();

                //初始化订单
                order = new Order(orderDto);


                int totalNum = 0;

                // 获取RecyclerView中各项的内容，设置各尺码下单数量
                for (int i = 0; i < addOrderAdapter.getItemCount(); i++) {
                    setOrderSkuNum(addOrderAdapter.orderInfoList.get(i).getTitle(), addOrderAdapter.orderInfoList.get(i).getFinalNum());
                    totalNum += addOrderAdapter.orderInfoList.get(i).getFinalNum();
                }

                if (totalNum <= 0) {
                    Toast.makeText(EditOrderActivity.this, "下单总数不可小于零", Toast.LENGTH_SHORT).show();
                    hideLoading();
                    return;
                }

                String orderString = new Gson().toJson(order);

                Log.d("orderString", orderString);

                OkHttpUtil.getInstance().doPostJson("/order/updateOrder", new DoCallBack() {
                    @Override
                    public void onSuccess(String result) {

                        Log.d("editOrder", result);
                        hideLoading();

                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("updatedOrder", order.getOrderId()); // 假设这是你需要传递的库存数据
                        setResult(Activity.RESULT_OK, resultIntent);
                        EditOrderActivity.this.finish(); // 关闭当前Activity

                    }

                    @Override
                    public void onError(Exception e) {
                        Log.d("updateOrder", "error");
                        Toast.makeText(EditOrderActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                    }
                }, orderString);

            }
        });

        binding.addOrderBatchStockSetting.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {

                // 创建Dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(EditOrderActivity.this);
                builder.setTitle("输入下单数量");

                // 使用LayoutInflater加载自定义布局
                LayoutInflater inflater = getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.dialog_add_order_batch_number, null);
                builder.setView(dialogView);

                // 获取输入框和按钮
                final EditText inputNumber = dialogView.findViewById(R.id.dialog_add_order_batch_number_input_number);
                Button btnCancel = dialogView.findViewById(R.id.dialog_add_order_batch_BtnCancel);
                Button btnConfirm = dialogView.findViewById(R.id.dialog_add_order_batch_BtnConfirm);

                // 创建并显示Dialog
                AlertDialog dialog = builder.create();
                dialog.show();

                // 设置取消按钮点击事件
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                // 设置确认按钮点击事件
                btnConfirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String input = inputNumber.getText().toString();
                        if (!input.isEmpty()) {
                            int number = Integer.parseInt(input);
                            // 处理输入的数字
                            handleInputNumber(number);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(EditOrderActivity.this, "请输入一个有效的数字", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });

        binding.editOrderDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(EditOrderActivity.this);
                builder.setTitle("确认删除");
                builder.setMessage("确定删除<" + orderDto.getTitle() + ">吗?");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        HashMap<String, String> merMap = new HashMap<>();
                        merMap.put("orderId", orderDto.getOrderId());
                        // 执行删除操作，例如从数据集中移除对应项
                        OkHttpUtil.getInstance().doPostForm("/order/delete", new DoCallBack() {
                            @Override
                            public void onSuccess(String result) {
                                Log.d("Order Delete", result);
//                                remove(getItem(position));
//                                merchandiseList.remove(position);
//                                List<Merchandise> update = new ArrayList<>();
//                                update.addAll(merchandiseList);
//                                update.remove(position);
//                                merchandiseList = update;
//                                notifyDataSetChanged();
                                dialog.dismiss();
                                EditOrderActivity.this.finish();
                            }

                            @Override
                            public void onError(Exception e) {
                                Log.d("tag", "Mer Delete error");
                                Toast.makeText(EditOrderActivity.this, "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
                            }
                        }, merMap);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });

    }

    // 处理输入的数字
    @SuppressLint("NotifyDataSetChanged")
    private void handleInputNumber(int number) {

        // 更改RecyclerView中各项的内容，设置FinalNum数量
        for (OrderInfo orderInfo : addOrderAdapter.orderInfoList) {
            orderInfo.setFinalNum(number);
        }

        addOrderAdapter.notifyDataSetChanged();
        // 在这里处理输入的数字，例如更新订单数量
//        Toast.makeText(this, "输入的数字是: " + number, Toast.LENGTH_SHORT).show();
    }

    private void setOrderSkuNum(String title, int stock) {
        if (title.equals("XXS")) {
            order.setMake_XXS(Math.max(stock, 0));
            order.setActivate_XXS(1);
        }
        if (title.equals("XS")) {
            order.setMake_XS(Math.max(stock, 0));
            order.setActivate_XS(1);
        }
        if (title.equals("S")) {
            order.setMake_S(Math.max(stock, 0));
            order.setActivate_S(1);
        }
        if (title.equals("M")) {
            order.setMake_M(Math.max(stock, 0));
            order.setActivate_M(1);
        }
        if (title.equals("L")) {
            order.setMake_L(Math.max(stock, 0));
            order.setActivate_L(1);
        }
        if (title.equals("XL")) {
            order.setMake_XL(Math.max(stock, 0));
            order.setActivate_XL(1);
        }
        if (title.equals("XXL")) {
            order.setMake_XXL(Math.max(stock, 0));
            order.setActivate_XXL(1);
        }
        if (title.equals("0XL")) {
            order.setMake_Plus_0XL(Math.max(stock, 0));
            order.setActivate_Plus_0XL(1);
        }
        if (title.equals("1XL")) {
            order.setMake_Plus_1XL(Math.max(stock, 0));
            order.setActivate_Plus_1XL(1);
        }
        if (title.equals("2XL")) {
            order.setMake_Plus_2XL(Math.max(stock, 0));
            order.setActivate_Plus_2XL(1);
        }
        if (title.equals("3XL")) {
            order.setMake_Plus_3XL(Math.max(stock, 0));
            order.setActivate_Plus_3XL(1);
        }
        if (title.equals("4XL")) {
            order.setMake_Plus_4XL(Math.max(stock, 0));
            order.setActivate_Plus_4XL(1);
        }
        if (title.equals("5XL")) {
            order.setMake_Plus_5XL(Math.max(stock, 0));
            order.setActivate_Plus_5XL(1);
        }
        if (title.equals("6XL")) {
            order.setMake_Plus_6XL(Math.max(stock, 0));
            order.setActivate_Plus_6XL(1);
        }
    }


    private void setMerMap(OrderDto orderDto) {
        if (orderDto.getActivate_XXS() == 1) {
            OrderInfo orderInfo = new OrderInfo("XXS", orderDto.getFirstImage(), orderDto.getMake_XXS(), orderDto.getXXS());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_XS() == 1) {
            OrderInfo orderInfo = new OrderInfo("XS", orderDto.getFirstImage(), orderDto.getMake_XS(), orderDto.getXS());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_S() == 1) {
            OrderInfo orderInfo = new OrderInfo("S", orderDto.getFirstImage(), orderDto.getMake_S(), orderDto.getS());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_M() == 1) {
            OrderInfo orderInfo = new OrderInfo("M", orderDto.getFirstImage(), orderDto.getMake_M(), orderDto.getM());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_L() == 1) {
            OrderInfo orderInfo = new OrderInfo("L", orderDto.getFirstImage(), orderDto.getMake_L(), orderDto.getL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("XL", orderDto.getFirstImage(), orderDto.getMake_XL(), orderDto.getXL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_XXL() == 1) {
            OrderInfo orderInfo = new OrderInfo("XXL", orderDto.getFirstImage(), orderDto.getMake_XXL(), orderDto.getXXL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_0XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("0XL", orderDto.getFirstImage(), orderDto.getMake_Plus_0XL(), orderDto.getPlus_0XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_1XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("1XL", orderDto.getFirstImage(), orderDto.getMake_Plus_1XL(), orderDto.getPlus_1XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_2XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("2XL", orderDto.getFirstImage(), orderDto.getMake_Plus_2XL(), orderDto.getPlus_2XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_3XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("3XL", orderDto.getFirstImage(), orderDto.getMake_Plus_3XL(), orderDto.getPlus_3XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_4XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("4XL", orderDto.getFirstImage(), orderDto.getMake_Plus_4XL(), orderDto.getPlus_4XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_5XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("5XL", orderDto.getFirstImage(), orderDto.getMake_Plus_5XL(), orderDto.getPlus_5XL());
            orderInfoList.add(orderInfo);
        }
        if (orderDto.getActivate_Plus_6XL() == 1) {
            OrderInfo orderInfo = new OrderInfo("6XL", orderDto.getFirstImage(), orderDto.getMake_Plus_6XL(), orderDto.getPlus_6XL());
            orderInfoList.add(orderInfo);
        }
    }

    private void showLoading() {
        binding.AddOrderEditMerStockLoadingProgressBar.setVisibility(View.VISIBLE);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    private void hideLoading() {
        binding.AddOrderEditMerStockLoadingProgressBar.setVisibility(View.GONE);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

}